package org.example.lotterysystem.common.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    StringRedisTemplate stringRedisTemplate=new StringRedisTemplate();
    private final Logger logger= LoggerFactory.getLogger(RedisUtil.class);


    /**
     * 设置值
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,String value){
        try{
            stringRedisTemplate.opsForValue().set(key,value);
            return true;
        }catch(Exception e){
            logger.error("Redis设置值失败,e:{}key:{} value:{}",e,key,value);
            return false;
        }
    }

    /**
     * Redis中获取值
     * @param key
     * @return
     */
    public String get(String key){
        try {
            return StringUtils.hasText(key) ? stringRedisTemplate.opsForValue().get(key):null;
        }catch (Exception e){
            logger.error("Redis获取值失败,Key{}:",key,e);
            return null;
        }
    }

    /**
     * 给要存储的值设置过期时间
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key,String value,Long time){
        try{
            stringRedisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
            return true;
        }catch (Exception e){
            logger.error("Redis设置过期时间值失败e:{}key:{}value:{}",e,key,value);
            return false;
        }
    }

    /**
     *
     * 删除一个或者多个值
     * @param key
     * @return
     */
    public boolean delete(String... key){
        try {
            if(null!=key&&key.length>0){
                if(key.length==1){
                    stringRedisTemplate.delete(key[0]);
                }else{
                    stringRedisTemplate.delete((Collection<String>)CollectionUtils.arrayToList(key));
                }
            }
            return true;
        }catch (Exception e){
            logger.error("Redis删除值Exception",e);
            return false;
        }
    }

    public boolean hasKey(String key){
        try {
            return StringUtils.hasText(key)? stringRedisTemplate.hasKey(key):false;

        }catch (Exception e){
            logger.error("判断是否存在值异常:",e);
            return false;
        }
    }
}
